<?php

namespace app\api\controller\shop;
use app\admin\model\Devicelock;
use app\admin\model\Org;
use app\admin\model\Shopbalanceprofit;
use app\admin\model\Shopcoupon;
use app\admin\model\Shopdevice;
use app\admin\model\Shopdiscount;
use app\admin\model\Shopdou;
use app\admin\model\Shopmeituan;

use app\admin\model\Shopmno;
use app\admin\model\Shopmtdyprofit;
use app\admin\model\Shoporder;
use app\admin\model\Shoproom;
use app\admin\model\Shoproombook;
use app\admin\model\Shoproomset;
use app\admin\model\Shoptuan;
use app\admin\model\Userallbalance;
use app\admin\model\Userbalance;
use app\admin\model\Usercoupon;
use app\admin\model\Userdiscount;
use app\admin\model\Userdoucode;
use app\admin\model\Usermeituancode;

use app\admin\model\Userorderprofit;
use app\admin\model\Usertuan;

use app\admin\model\Userweixin;
use app\api\service\CfService;
use app\api\service\CurlService;

use app\api\service\DouService;
use app\api\service\LockService;
use app\api\service\MeituanService;

use app\api\service\MtService;
use app\api\service\RoomService;
use app\api\service\VbillService;
use app\common\controller\Api;
use function EasyWeChat\Kernel\Support\get_client_ip;

/**
 */
class Orderbook extends Api
{
    protected $noNeedLogin = [ 'sxfOrderCallback', 'orderInit'];
    protected $noNeedRight = '*';

    protected $app = null;

    public function _initialize()
    {
        parent::_initialize();

    }

    public function orderInit()
    {

        $id = $this->request->param('id');
        $date = $this->request->param('date');
        $startTime = $this->request->param('startTime');
        $hour = $this->request->param('hour');
        $type = $this->request->param('type');
        $shopRoomModel = new Shoproom();
        $room = $shopRoomModel->where('id', $id)->find();
        $tuanId = $this->request->param('tuanId');
        $mtCode = $this->request->param('mtCode');
        $douCode = $this->request->param('douCode');
        $couponId = $this->request->param('couponId');
        $discountId = $this->request->param('discountId');
        if ($discountId == "") $discountId = -1;

        if(!$hour) $hour = 1;
        $setId = $this->request->param('setId');

        $start = explode("-", $startTime)[0];

        if ($date == '') {
            $date = date("Y-m-d");
        }

        //判断是否营销套餐
        $isSaleSet = -1;
        if ($setId != "") {
            $roomSetModel = new Shoproomset();
            $set = $roomSetModel->where('id', $setId)->find();
            if ($set['time'] != "") $isSaleSet = 1;

        }
        $startCompareTime = strtotime($date . " " . $start);

        if ($startCompareTime <= strtotime("-10 minute") && $isSaleSet == 1) {

            $date = date("Y-m-d", strtotime("+1 day", strtotime($date)));
            $startCompareTime = strtotime($date . " " . $start);

        } else if ($startCompareTime <= strtotime("-10 minute") && $isSaleSet == -1) {

            $start = date("H:i");
        }

        $time = array();
        $hourArray = array();
        $newSetList = array();
        $roomSet = array();
        $totalPrice = 0;

        $time = getFiveDate();
        foreach ($time as $key => $val) {
            $time[$key]['selected'] = false;
            if ($val['dateValue'] == $date) {
                $time[$key]['selected'] = true;
            }
        }

        $per_amount = 0;//增加一个单价，方便后面时长抵扣券计算
        if ($type == 0) {
            $hourArray = array();
            for ($i = 0; $i <= 3; $i++) {
                $hourArray[] = $room['min_book_hour'] + $i;
            }
            $per_amount = $room['hour_price'];
            $totalPrice = $hour * $room['hour_price'];
        } else {
            $per_amount = $room['hour_price'];
            $totalPrice = $hour * $room['hour_price'];
            $roomSetModel = new Shoproomset();
            $roomSet = $roomSetModel->where('room_id', $id)->where('time', '')->order('weigh', 'desc')->order('hour', 'asc')->select();

            $newSetList = $roomSetModel->where('room_id', $id)->where('time', '<>', '')->order('weigh', 'desc')->order('hour', 'asc')->select();

//            foreach ($roomSet as $key => $val) {
//                if ($hour == $val['hour']) {
//                    $per_amount = ceil($val['amount'] / $val['hour'] * 100) / 100;
//                    $totalPrice = $val['amount'];
//                    break;
//                }
//            }

            if ($setId != "") {
                $set = $roomSetModel->where('id', $setId)->find();
                if ($set) {
                    $per_amount = ceil($set['amount'] / $set['hour'] * 100) / 100;
                    $totalPrice = $set['amount'];
                }
            }
        }
        $user = $this->auth->getUser();
        $userBalanceModel = new Userbalance();
        $balance = $userBalanceModel->balance($room['shop_id'], $user['id']);

        $userAllBalanceModel = new Userallbalance();
        $allBalance = $userAllBalanceModel->userBalance($user['id']);
        $ret = array();
        $ret['name'] = $room['name'];
        $ret['logo'] = cdnurl($room['logo']);
        $ret['date'] = $time;
        $ret['set'] = $roomSet;
        $ret['yh_set'] = $newSetList;
        $ret['selectDate'] = $date;
        $ret['hours'] = $hourArray;
        $ret['book_hour'] = $hour;
        $ret['balance'] = formatMoney($balance + $allBalance);
        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id', $room['shop_id'])->find();
        if ($shop['is_join_balance'] == 1) {
            $balance = formatMoney($balance + $allBalance);
        }

        $ret['startTime'] = $start;
        $ret['book_price'] = $room['hour_price'];
        $min = $hour * 60;
        $d = date("H:i", strtotime("+" . $min . " minute", strtotime($date . " " . $start)));

        $ret['endTime'] = $d;

        $ret['start'] = date("Y-m-d H:i", $startCompareTime);
        $ret['end'] = date("Y-m-d H:i", strtotime("+" . $min . " minute", strtotime($date . " " . $start)));


        $dayTime = strtotime($date . " " . $ret['startTime']);
        $day = date("w", $dayTime);
        if ($day == 0) {
            $day = 7;
        }

        $yxList = array();
        foreach ($newSetList as $key=>$val){

            $set_time = $val['time'] . '~' . $val['end_time'];
            $isCheckSetTimeWeek = false;
            $isCheckSetTimeTime = false;
            if (in_array($day, json_decode($val['week'],true))) {
                $isCheckSetTimeWeek = true;
            }
            if($val['time'] == '00:00' && $val['end_time'] == '23:59'){
                $isCheckSetTimeTime = true;
            }else{
                if ($this->checkUseTime(strtotime($ret['start']), strtotime($ret['end']), $set_time)) {
                    $isCheckSetTimeTime = true;
                }
            }

            if($isCheckSetTimeTime == true && $isCheckSetTimeWeek == true){
                $yxList[] = $val;
            }

        }
        $ret['yh_set'] = $yxList;


        $tuanUserModel = new Usertuan();
        $shopTuanModel = new Shoptuan();

        /**
         * 团购券使用价格计算
         */


        if ($tuanId != -1 && $mtCode == '' && $douCode == '') {
            $userTuan = $tuanUserModel->where('id', $tuanId)->find();

            if ($userTuan) {


                if ($userTuan['valid_time'] > time() && $userTuan['status'] == 'unuse') {
                    $tuan = $shopTuanModel->where('id', $userTuan['tuan_id'])->find();

                    if ($tuan) {
                        $tuanHour = $tuan['hour'];

                        if ($tuanHour >= $hour) {
                            $totalPrice = 0;
                        } else {
                            $totalPrice = ($hour - $tuanHour) * $room['hour_price'];
                        }
                    }

                }
            }
        }
        $pay_price = $totalPrice;
        $userCouponModel = new Usercoupon();
        if ($couponId != -1 && $mtCode == '' && $douCode == '') {
            $userCoupon = $userCouponModel->where('id', $couponId)->find();
            $shopCouponModel = new Shopcoupon();
            $shopCoupon = $shopCouponModel->where('id', $userCoupon['coupon_id'])->find();
            if ($userCoupon['valid_time'] > time() && $userCoupon['status'] == 'unuse') {

                $pay_price = $totalPrice - $shopCoupon['amount'];
            }
        }
        $msg = "";

        if ($mtCode != '') {
            $userMtCodeModel = new Usermeituancode();
            $shopmeituan = new Shopmeituan();

            $mtCode = str_replace(" ", "", $mtCode);
            $meituanCode = $mtCode;
            $mtCode = $userMtCodeModel->where('mt_code', $mtCode)->find();
            if (!$mtCode) {

                $req = array();
                $req['code'] = $meituanCode;
                $req['shop_id'] = $room['shop_id'];

                $meituanService = new MeituanService();
                $mtInfo = $meituanService->prepare($req);

                if ($mtInfo['code'] == 200) {
                    $meituanUserCodeModel = new Usermeituancode();
                    $mtCode = $meituanUserCodeModel->where('mt_code', $meituanCode)->find();
                    if ($mtCode['status'] == 'unuse') {
                        $meituanUserCodeModel->where('id', $mtCode['id'])->delete();
                        $mtCode = $meituanUserCodeModel->where('mt_code', $meituanCode)->find();
                    }
                    $meituanModel = new Shopmeituan();
                    $meituan = $meituanModel->where('shop_id', $room['shop_id'])->where('dealgroup_id', $mtInfo['data']['dealgroup_id'])->find();
                    if (!$mtCode) {
                        $meituanUserCodeModel->insertGetId(['user_id' => $user['id'], 'mt_code' => $meituanCode,
                            'create_time' => time(), 'status' => 'unuse', 'order_id' => -1, 'group_id' => $meituan['id'], 'shop_id' => $meituan['shop_id']]);

                    } else {
                    }
                    $mtCode = $meituanUserCodeModel->where('mt_code', $meituanCode)->find();
                }
            }

            if ($mtCode['status'] == 'unuse') {
                $meituan = $shopmeituan->where('id', $mtCode['group_id'])->find();

                if (!$meituan) $this->error("此券数据不存在");

                $time = $meituan['use_time'];
                $start = explode("~", $time)[0];
                $end = explode("~", $time)[1];


                $bookStart = strtotime($date . " " . $ret['startTime']);
                $bookEnd = strtotime($date . " " . $ret['endTime']);

                if ($bookStart > $bookEnd) {
                    $date2 = date("Y-m-d", strtotime("+1 day", $bookStart));

                    $bookEnd = strtotime($date2 . " " . $ret['endTime']);
                }

                $startTime = strtotime($date . " " . $start);
                $endTime = strtotime($date . " " . $end);

                $isTime = false;
                if ($bookStart >= $startTime && $bookEnd <= $endTime) {
                    $isTime = true;
                }
                if ($start == '00:00' && $end == "23:59") {
                    $isTime = true;
                }

                $roomIds = json_decode($meituan['room_id'], true);

                $isExist = false;
                foreach ($roomIds as $key => $val) {
                    if ($id == $val) {
                        $isExist = true;
                    }
                }

                $week = json_decode($meituan['week'], true);
                $isWeek = false;
                foreach ($week as $k2 => $v2) {
                    if ($v2 == $day) {
                        $isWeek = true;
                        break;
                    }
                }
                if ($isWeek == false || $isTime == false) {
                    $msg = "预定时间不在券使用范围内";
                }

                if ($isWeek && $isTime && $isExist) {
                    if ($meituan['hour'] >= $hour) {
                        $totalPrice = 0;
                    } else {
                        $totalPrice = ($hour - $meituan['hour']) * $room['hour_price'];
                    }
                } else {

                }


            }

        }
        if ($douCode != '') {
            $userDouCodeModel = new Userdoucode();
            $shopDouModel = new Shopdou();
            $douCodeDb = $userDouCodeModel->where('dou_code', $douCode)->find();
            if (!$douCodeDb) {
                $dou_code = $douCode;
                $curlService = new CurlService();
                $tokenUrl = "https://open.douyin.com/oauth/client_token/";
                $tokenReq = array();
                $tokenReq["client_key"] = "awoh1q4tfg29z1yv";
                $tokenReq["client_secret"] = "b8976219b329b01d543e76a83c923720";
                $tokenReq["grant_type"] = "client_credential";

                $result = $curlService->curl_post($tokenUrl, $tokenReq);
                $token = $result['data']['access_token'];

                if (substr($dou_code, 0, 5) == "https") {

                    $headers = get_headers($dou_code, TRUE);
                    $reqUrl = $headers['Location'];
                    $data = parse_url($reqUrl);
                    parse_str($data['query'], $results);
                    $objData = $results['object_id'];
                    $url = "https://open.douyin.com/goodlife/v1/fulfilment/certificate/prepare/?encrypted_data=" . $objData;
                } else {
                    $url = "https://open.douyin.com/goodlife/v1/fulfilment/certificate/prepare/?code=" . $dou_code;
                }


                $result = $curlService->http_curl_get($url, $token);

                if ($result['data']['error_code'] != 0) {
                    $this->error($result['data']['description']);
                }
                $certificates = $result['data']['certificates'];
                if (count($certificates) == 0) {
                    $this->error("此券码错误");
                }

                $skuId = $certificates[0]['sku']['sku_id'];

                $shopDouModel = new Shopdou();
                $shopDou = $shopDouModel->where('sku_id', $skuId)->find();
                if (!$shopDou) $this->error("店铺未同步该券产品，请联系商家");


                $douUserCodeModel = new Userdoucode();
                $userCode = $douUserCodeModel->where('dou_code', $dou_code)->find();
                if (!$userCode) {
                    $douUserCodeModel->insertGetId(['user_id' => $user['id'], 'dou_code' => $dou_code, 'create_time' => time(), 'sku_id' => $skuId, 'shop_id' => $shop['id']]);
                } else {
                    $douUserCodeModel->where('id', $userCode['id'])->update(['user_id' => $user['id'], 'dou_code' => $dou_code, 'create_time' => time(), 'sku_id' => $skuId, 'shop_id' => $shop['id']]);
                    $userCode['id'];
                }
                $douCodeDb = $userDouCodeModel->where('dou_code', $dou_code)->find();


            }
            if ($douCodeDb['status'] == 'unuse') {
                $dou = $shopDouModel->where('shop_id', $room['shop_id'])->where('sku_id', $douCodeDb['sku_id'])->find();
                if (!$dou) $this->error("此券数据不存在");
                $roomIds = json_decode($dou['room_id'], true);

                $isExist = false;
                foreach ($roomIds as $key => $val) {
                    if ($id == $val) {
                        $isExist = true;
                    }
                }
                $time = $dou['use_time'];
                $start = explode("~", $time)[0];
                $end = explode("~", $time)[1];


                $bookStart = strtotime($date . " " . $ret['startTime']);
                $bookEnd = strtotime($date . " " . $ret['endTime']);


                $bookStart = strtotime($date . " " . $ret['startTime']);
                $bookEnd = strtotime($date . " " . $ret['endTime']);

                if ($bookStart > $bookEnd) {
                    $date2 = date("Y-m-d", strtotime("+1 day", $bookStart));

                    $bookEnd = strtotime($date2 . " " . $ret['endTime']);
                }

                $startTime = strtotime($date . " " . $start);
                $endTime = strtotime($date . " " . $end);


                $isTime = false;
                if ($bookStart >= $startTime && $bookEnd <= $endTime) {
                    $isTime = true;
                }
                if ($start == '00:00' && $end == "23:59") {
                    $isTime = true;
                }
                $week = json_decode($dou['week'], true);
                $isWeek = false;
                foreach ($week as $k2 => $v2) {
                    if ($v2 == $day) {
                        $isWeek = true;
                        break;
                    }
                }


                if ($isWeek == false || $isTime == false) {
                    $msg = "预定时间不在券使用范围内";
                }

                //error_log($isWeek."======orderIninit2====".$isTime."====ss===".$isExist);
                if ($isWeek && $isTime && $isExist) {
                    if ($dou['hour'] >= $hour) {
                        $totalPrice = 0;
                    } else {
                        $totalPrice = ($hour - $dou['hour']) * $room['hour_price'];
                    }
                } else {
                    $ret['douCode'] = "";
                }
            }

        }

        $ret['douCode'] = $douCode;
        $ret['total_price'] = round($totalPrice, 2);

        $ret['status'] = $room['status'];
        $ret['orderEndTime'] = "";

        if ($room['status'] == 'busy') {

            $bookRoomModel = new Shoproombook();
            $roomBook = $bookRoomModel->where('room_id', $room['id'])->where('status', 'doing')->order('id', 'desc')->find();
            if ($roomBook) {
                $ret['orderEndTime'] = date("H:i", $roomBook['end_time']);
            }
        }

        /**
         * 判断是和已预定的时间冲突
         */
        $time1 = strtotime($date . " " . $ret['startTime']);
        $time2 = strtotime($date . " " . $ret['endTime']);

        if ($time2 < $time1) {
            $date2 = date("Y-m-d", strtotime("+1 day", $time1));
            $time2 = strtotime($date2 . " " . $ret['endTime']);
        }

        $userCouponModel = new Usercoupon();
        if ($couponId != -1) {
            $couponList = array();
            $coupon = $userCouponModel->with(['coupon'])->where('coupon_id', $couponId)->find();
            $couponList[] = $coupon;
        } else {
            $couponList = $userCouponModel->checkCoupon($id, $user['id'], $time1, $time2, $pay_price);
        }
        $ret['couponList'] = $couponList;

        $dis_price = 0;
        if ($tuanId == -1 && $couponId == -1) {

            if ($balance >= $totalPrice) {
                $dis_price = $totalPrice;
                $pay_price = 0;
            } else {
                $dis_price = $balance;
                $pay_price = $totalPrice - $balance;
            }

        }
        $ret['pay_price'] = round($pay_price, 2);
        $ret['dis_price'] = round($dis_price, 2);

        $shopRoomBookModel = new Shoproombook();
        $checkStart = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $id)->where('start_time', "<=", $time1)->where("end_time", ">=", $time1)->find();
        $checkEnd = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $id)->where('start_time', "<=", $time2)->where("end_time", ">=", $time2)->find();
        $checkEnd3 = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $id)->where('start_time', ">=", $time1)->where("end_time", "<=", $time2)->find();

        if ($checkStart != null || $checkEnd != null || $checkEnd3 != null) {
            $msg = "此时间段已预定";
        }

        /**
         * 团购券检测可用
         */
        $tuanList = $tuanUserModel->checkTuan2($id, $user['id'], $time1, $time2);
        foreach ($tuanList as $key => $val) {
            $tuanList[$key]['end_date'] = date("Y-m-d", strtotime("+" . $val['tuan']['valid_day'] . " day", $val['create_time']));

        }
        $ret['tuanList'] = $tuanList;
        $ret['shop_name'] = $shop['name'];
        $ret['discount'] = [];

        $userDiscountModel = new Userdiscount();
        $discountModel = new Shopdiscount();
        if ($discountId == -1) {

            $checkDiscountList = array();
            $discountList = $userDiscountModel->where('user_id', $user['id'])->where('status', 1)->where('valid_time', ">", time())->select();
            foreach ($discountList as $key => $val) {

                $discountId = $val['id'];
                $discount = $discountModel->where('id', $val['discount_id'])->find();
                $discount['id'] = $val['id'];
                $discount['discount_id'] = $val['discount_id'];

                $rule = json_decode($discount['rule'], true);


                $start = explode("~", $rule['time'])[0];
                $end = explode("~", $rule['time'])[1];

                $bookStart = $time1;
                $bookEnd = $time2;

                $startTime = strtotime($date . " " . $start);
                $endTime = strtotime($date . " " . $end);

                $isTime = false;
                if ($bookStart >= $startTime && $bookEnd <= $endTime) {
                    $isTime = true;
                }
                if ($start == '00:00' && $end == "23:59") {
                    $isTime = true;
                }
                $week = $rule['week'];
                $isWeek = false;
                foreach ($week as $k2 => $v2) {
                    if ($v2 == $day) {
                        $isWeek = true;
                        break;
                    }
                }
                $isRoom = false;
                $roomList = $rule['room'];
                foreach ($roomList as $key => $val) {
                    if ($val == $id) {
                        $isRoom = true;
                    }
                }


                if ($isRoom && $isWeek && $isTime) {

                    $checkDiscountList[] = $discount;

                }

            }
            $ret['discount'] = $checkDiscountList;

        } else {
            $userDiscount = $userDiscountModel->where('id', $discountId)->find();
            $discount = $discountModel->where('id', $userDiscount['discount_id'])->find();

            $rule = json_decode($discount['rule'], true);


            $start = explode("~", $rule['time'])[0];
            $end = explode("~", $rule['time'])[1];

            $bookStart = $time1;
            $bookEnd = $time2;

            $startTime = strtotime($date . " " . $start);
            $endTime = strtotime($date . " " . $end);

            $isTime = false;
            if ($bookStart >= $startTime && $bookEnd <= $endTime) {
                $isTime = true;
            }
            if ($start == '00:00' && $end == "23:59") {
                $isTime = true;
            }
            $week = $rule['week'];
            $isWeek = false;
            foreach ($week as $k2 => $v2) {
                if ($v2 == $day) {
                    $isWeek = true;
                    break;
                }
            }
            $isRoom = false;
            $roomList = $rule['room'];
            foreach ($roomList as $key => $val) {
                if ($val == $id) {
                    $isRoom = true;
                }
            }

            if ($isRoom && $isWeek && $isTime) {
                if ($discount['discount_type'] == '时长抵扣') {
                    if ($discount['discount_val'] >= $hour) {
                        $ret['pay_price'] = 0;
                    } else {
                        $diff_hour = $hour - $discount['discount_val'];
                        $ret['pay_price'] = $per_amount * $diff_hour;
                    }
                } else {
                    if ($discount['discount_type'] == '金额抵扣') {
                        $discoutPrice = $ret['pay_price'] - $discount['discount_val'];
                        if ($discoutPrice < 0) $discoutPrice = 0;
                        $ret['pay_price'] = $discoutPrice;
                    } else {
                        $ret['pay_price'] = formatMoney($ret['pay_price'] * $discount['discount_val'] / 10);
                    }

                }


            }


        }

        $this->success($msg, $ret);

    }



    protected function checkUseTime($bookSt, $bookEt, $useTime)
    {
        list($useSt, $useEt) = explode('~', $useTime);
        $date = date('Y-m-d', $bookSt);
        $z = strtotime($date . " 23:59:59");//判断每天最大时间节点

        $use_st = strtotime($date . " " . $useSt);
        $use_et = strtotime($date . " " . $useEt);
        if ($use_st > $use_et) {
            if ($bookEt <= $z) {
                if ($use_st <= $bookSt) {
                    $use_et += 86400;
                } else {
                    $use_st -= 86400;
                }
            } else {
                $use_et += 86400;
            }
        }
        if ($bookSt >= $use_st && $bookEt <= $use_et) {
            return true;
        }
        return false;
    }

    protected function isOverlap($start1, $end1, $start2, $end2): bool
    {
        if ($end1 < $start2 || $start1 > $end2) {
            return false;
        }
        return true;
    }




    public function addBookOrderFz()
    {
        $id = $this->request->param('id');
        $date = $this->request->param('date');
        $startTime = $this->request->param('startTime');
        $hour = $this->request->param('hour');
        $setId = $this->request->param('setId');//套餐ID 如果ID 为-1 就是时间预定
        $tuanId = $this->request->param('tuanId');
        $mt_code = $this->request->param('mtCode');
        $orgId = $this->request->param('orgId');
        $dou_code = $this->request->param('douCode');
        $couponId = $this->request->param('couponId');
        $discountId = $this->request->param('discountId');
        $mobile = $this->request->param('mobile');
        if($couponId == ''){
            $couponId = -1;
        }

        $mt_code = trim($mt_code);
        $dtime = strtotime($date);
        if($dtime <time()){
            $date = date("Y-m-d",time());
        }

        $day = date("w", strtotime($date));
        if ($day == 0) {
            $day = 7;
        }

        $userModel = new \app\admin\model\User();
        $user = $userModel->where('mobile',$mobile)->find();
        if(!$user){
            $db = array();
            $db['group_id'] = 1;
            $db['username'] = "微信用户";
            $db['mobile'] = $mobile;
            $db['createtime'] = time();
            $db['status'] = 'normal';
            $db['org_id'] = $orgId;
            $user_id = $userModel->insertGetId($db);
            $user = $userModel->where('id',$user_id)->find();
        }else{
            $user_id = $user['id'];
        }

        /**
         * 判断是和已预定的时间冲突
         */
        $time1 = strtotime($date . " " . $startTime);
        $min = $hour * 60;

        $endStrotime = strtotime("+" . $min . " minute", strtotime($date . " " . $startTime));

        if($time1 <time()) {
            $time1 = time();
            $endStrotime = strtotime("+" . $min . " minute", $time1);
        }

        $time2 = $endStrotime;


        $cacheKey  = "room_".$id;
        $cache = $this->redis->get($cacheKey);
        if($cache != false){
            $cacheObj =  $this->redis->get($cacheKey);
            $checkMowTime = strtotime("-60 seconds",time());
            $cache = json_decode($cacheObj,true);
            if(isset($cache['create_time']) && $cache['create_time'] <$checkMowTime){
                $this->redis->rm($cacheKey);
            }

            $start = $cache['start'];
            $end = $cache['end'];
            if($cache['user_id'] != $user['id']){
                $cacheCheck = -1;
                if($time1 <=$start &&  $time2 >= $end) $cacheCheck = 1;//全包围
                if($time1 >= $start && $time2 <= $end) $cacheCheck = 1;//在区间范围内
                if($time1 <= $end && $time2 >$end) $cacheCheck = 1; //
                if($time1 < $start && $time2 <=$end && $time2 >= $start) $cacheCheck = 1;
                if ($cacheCheck == 1) $this->error("请稍后提交，前面有客户正在预定");
            }
        }
        $cacheObj = array();
        $cacheObj['user_id'] = $user['id'];
        $cacheObj['start'] = $time1;
        $cacheObj['end'] = $time2;
        $cacheObj['create_time'] = time();

        $this->redis->set($cacheKey,json_encode($cacheObj));

        $isBooked = -1;
        $shopRoomBookModel = new Shoproombook();
        $bookList = $shopRoomBookModel->where('room_id',$id)->where('status','in',['undo','doing'])->order('start_time','desc')->select();
        foreach ($bookList as $key=>$val){

            $start = $val['start_time'];
            $end = $val['end_time'];
            if($time1 <=$start &&  $time2 >= $end) $isBooked = 1;//全包围
            if($time1 >= $start && $time2 <= $end) $isBooked = 1;//在区间范围内
            if($time1 <= $end && $time2 >$end) $isBooked = 1; //
            if($time1 < $start && $time2 <=$end && $time2 >= $start) $isBooked = 1;

        }
        if($isBooked == 1) $this->error("此时间段已被预定");

        $shopOrderModel = new Shoporder();
        $user = $this->auth->getUser();

        $checkMowTime = strtotime("-40 seconds",time());
        $isBookIng = -1;
        $checkBookList = $shopOrderModel->where('user_id',"<>",$user['id'])->where('status', 'in',['paying','payed'])->where('room_id', $id)->where('create_time',">=",$checkMowTime)->where('create_time',"<=",time())->select();

        foreach ($checkBookList as $key=>$val){

            $start = $val['book_start'];
            $end = $val['book_end'];

            if($time1 <=$start &&  $time2 >= $end) $isBookIng = 1;//全包围
            if($time1 >= $start && $time2 <= $end) $isBookIng = 1;//在区间范围内
            if($time1 <= $end && $time2 >$end) $isBookIng = 1; //
            if($time1 < $start && $time2 <=$end && $time2 >= $start) $isBookIng = 1;
        }
        if($isBookIng == 1){
            $this->error("此时间段正在有人预定，请稍后再试");
        }


        $shopRoomModel = new Shoproom();
        $room = $shopRoomModel->where('id', $id)->find();
        if($room['status'] == 'stop'){
            $this->error("此包厢正在维护中 不可预订");
        }
        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id', $room['shop_id'])->find();
        if($shop['status'] == 4){
            $this->error("店铺休息中 不可预订");
        }
        if($shop['status'] == 3){
            $this->error("店铺正在筹备中,敬请期待");

        }

        if($shop['open_time'] != ""){

            if (!$this->checkUseTime($time1, $time2, $shop['open_time'])) {
                $this->error('营业时间:【' . $shop['open_time'] . '】');
            }
        }


        if ($orgId == "") {
            $orgId = $shop['org_id'];
        }

        $orderPrice = 0;
        if ($setId == -1) {
            $totalPrice = $hour * $room['hour_price'];
            $orderPrice = $totalPrice;
        } else {
            $shopRoomBookSetModel = new Shoproomset();
            $set = $shopRoomBookSetModel->where('id', $setId)->find();
            if ($set['time'] != "") {
                if ($set['time'] != "00:00" || $set['end_time'] != "23:59") {
                    $set_time = $set['time'] . '~' . $set['end_time'];
                    if (!$this->checkUseTime($time1, $time2, $set_time)) {
                        $this->error('套餐使用时间: ' . $set_time);
                    }
                }
            }
            $totalPrice = $set['amount'];

            $orderPrice = $totalPrice;
        }
        $user = $this->auth->getUser();
        $userBalanceModel = new Userbalance();
        $balance = $userBalanceModel->balance($room['shop_id'], $user['id']);

        $tuanUserModel = new Usertuan();
        $shopTuanModel = new Shoptuan();
        if ($tuanId != -1 && $mt_code == "" && $dou_code == "") {
            $userTuan = $tuanUserModel->where('user_id', $user['id'])->where('id', $tuanId)->where('status', 'unuse')->order('valid_time', 'asc')->find();

            if ($userTuan) {
                if ($userTuan['valid_time'] > time() && $userTuan['status'] == 'unuse') {
                    $tuan = $shopTuanModel->where('id', $userTuan['tuan_id'])->find();

                    if ($tuan) {
                        $tuanHour = $tuan['hour'];
                        if ($tuanHour >= $hour) {
                            $totalPrice = 0;
                        } else {
                            $totalPrice = ($hour - $tuanHour) * $room['hour_price'];
                        }
                    }

                }
            }
        }

        if($couponId != -1 && $mt_code == "" && $dou_code == ""){
            $userCouponModel = new Usercoupon();
            $shopCouponModel = new Shopcoupon();
            $userCoupon = $userCouponModel->where('id', $couponId)->find();
            $shopCoupon = $shopCouponModel->where('id',$userCoupon['coupon_id'])->find();
            if ($userCoupon['valid_time'] > time() && $userCoupon['status'] == 'unuse') {
                $totalPrice = $orderPrice-$shopCoupon['amount'];
            }
        }
        $mtService = new MtService();
        $userMtCodeModel = new Usermeituancode();
        $meituanService= new MeituanService();
        $mtPayPrice = 0;//美团实际购买价格
        $douPayPrice = 0;//抖音实际购买价格
        $meituan_trace_id = "";
        $tmpHour = $hour;
        if ($mt_code != '') {
            $shopmeituan = new Shopmeituan();
            $mtCode = $userMtCodeModel->where('mt_code', $mt_code)->find();
            if (!$mtCode) $this->error("此券码不存在");
            if ($mtCode['status'] == 'unuse') {
                $meituan = $shopmeituan->where('id', $mtCode['group_id'])->find();
                if (!$meituan) $this->error("此券数据不存在");
                $mtPayPrice = $meituan['price'];
                $orderPrice = $mtPayPrice;

                $time = $meituan['use_time'];
                $start = explode("~", $time)[0];
                $end = explode("~", $time)[1];


                $bookStart = $time1;
                $bookEnd = $time2;

                $startTime = strtotime($date . " " . $start);
                $endTime = strtotime($date . " " . $end);
                $isTime = false;
                if ($bookStart >= $startTime && $bookEnd <= $endTime) {
                    $isTime = true;
                }

                if ($start == '00:00' && $end == "23:59") {
                    $isTime = true;
                }

                $roomIds = json_decode($meituan['room_id'], true);
                $isExist = false;
                foreach ($roomIds as $key => $val) {
                    if ($id == $val) {
                        $isExist = true;
                    }
                }
                $week = json_decode($meituan['week'], true);
                $isWeek = false;
                foreach ($week as $k2 => $v2) {
                    if ($v2 == $day) {
                        $isWeek = true;
                        break;
                    }
                }

                if ($isWeek && $isTime && $isExist) {
                    $tmpHour = $meituan['hour'];
                    if ($meituan['hour'] >= $hour) {
                        $totalPrice = 0;
                    } else {
                        $totalPrice = ($hour - $meituan['hour']) * $room['hour_price'];
                    }
                } else {

                }

            }

            //官方校验美团券
            $mtReq = array();
            $mtReq['shop_id'] = $shop['id'];
            $mtReq['code'] = $mt_code;

            if($shop['mt2_token'] != ""){
                $mtInfo = $meituanService->prepare($mtReq);
                $meituan_trace_id = $mtInfo['traceId'];
            }else{
                $mtInfo = $mtService->couponInfo($mtReq);

            }

            if ($mtInfo['code'] != 200) {
                $userMtCodeModel->where('mt_code', $mtCode)->update(['status' => 'bad']);
                $mt_code = "";
                $this->error("此券不用");
            }
        }

        $douVerifyToken = "";
        if ($dou_code != '') {
            $userDouCodeModel = new Userdoucode();
            $shopDouModel = new Shopdou();
            $douCodeDb = $userDouCodeModel->where('dou_code', $dou_code)->find();
            if (!$douCodeDb) $this->error("此券码不存在");
            if ($douCodeDb['status'] == 'unuse') {
                $dou = $shopDouModel->where('shop_id',$room['shop_id'])->where('sku_id', $douCodeDb['sku_id'])->find();
                if (!$dou) $this->error("此券数据不存在");
                $orderPrice = $dou['price'];

                $roomIds = json_decode($dou['room_id'], true);
                $isExist = false;
                foreach ($roomIds as $key => $val) {
                    if ($id == $val) {
                        $isExist = true;
                    }
                }
                $time = $dou['use_time'];
                $start = explode("~", $time)[0];
                $end = explode("~", $time)[1];


                $bookStart = $time1;
                $bookEnd = $time2;

                $startTime = strtotime($date . " " . $start);
                $endTime = strtotime($date . " " . $end);


                $isTime = false;


                if ($bookStart >= $startTime && $bookEnd <= $endTime) {
                    $isTime = true;
                }
                if ($start == '00:00' && $end == "23:59") {
                    $isTime = true;
                }

                $week = json_decode($dou['week'], true);
                $isWeek = false;
                foreach ($week as $k2 => $v2) {
                    if ($v2 == $day) {
                        $isWeek = true;
                        break;
                    }
                }


                if ($isWeek && $isTime && $isExist) {


                    $douService = new DouService();
                    $douCheckRet = $douService->orderCheckCode($dou_code);

                    $douVerifyToken= $douCheckRet['token'];
                    $orderPrice = $douCheckRet['price'];
                    if ($douVerifyToken == '') {
                        $this->error("此券为无效券");
                    }
                    $tmpHour = $dou['hour'];
                    if ($dou['hour'] >= $hour) {
                        $totalPrice = 0;
                    } else {
                        $totalPrice = ($hour - $dou['hour']) * $room['hour_price'];
                    }

                } else {
                    $this->error("此券不能可用");
                }
            }

        }
        $userDiscountModel = new Userdiscount();
        if($discountId != ""){

            $shopDiscountModel = new Shopdiscount();
            $userDiscount = $userDiscountModel->where('id',$discountId)->where('status',1)->find();
            if(!$userDiscount) $this->error("此券已使用");
            $discount = $shopDiscountModel->where('id',$userDiscount['discount_id'])->find();
            $rule = json_decode($discount['rule'],true);


            $start = explode("~", $rule['time'])[0];
            $end = explode("~", $rule['time'])[1];

            $bookStart = $time1;
            $bookEnd = $time2;

            $startTime = strtotime($date . " " . $start);
            $endTime = strtotime($date . " " . $end);

            $isTime = false;
            if ($bookStart >= $startTime && $bookEnd <= $endTime) {
                $isTime = true;
            }
            if ($start == '00:00' && $end == "23:59") {
                $isTime = true;
            }
            $week = $rule['week'];
            $isWeek = false;
            foreach ($week as $k2 => $v2) {
                if ($v2 == $day) {
                    $isWeek = true;
                    break;
                }
            }
            $isRoom = false;
            $roomList = $rule['room'];
            foreach ($roomList as $key=>$val){
                if($val == $id){
                    $isRoom = true;
                }
            }

            if($isRoom && $isTime && $isWeek){
                if($discount['discount_type'] == '时长抵扣'){
                    if($discount['discount_val'] >= $hour){
                        $totalPrice = 0;
                    }else{
                        if($setId != -1){
                            $setPrice =  $set['amount']/$set['hour'];
                            $haveHour = $hour -$discount['discount_val'];
                            $totalPrice = formatMoney($setPrice*$haveHour);
                        }

                    }

                }else if($discount['discount_type'] == '金额抵扣'){
                    $totalPrice = $totalPrice-$discount['discount_val'];
                    if($totalPrice <0) $totalPrice = 0;

                }else{
                    $totalPrice = formatMoney($totalPrice*$discount['discount_val']/10);
                }

            }



        }

        $pay_price = $totalPrice;
        $type = "";
        $dis_price = 0;
        $balanceReduce = 0;
        $allBalanceModel = new Userallbalance();
        $allBalance = $allBalanceModel->userBalance($user['id']);
        if ($totalPrice > 0) {

            if (($balance > 0 || $allBalance >0) && $mt_code == "" && $dou_code == "" && $couponId == -1 ) {
                $type = "balance";
                if($shop['is_join_balance'] == 1){
                    if ($balance >= $totalPrice) {
                        //1. 店铺余额大于 订单余额
                        $dis_price = $totalPrice;
                        $pay_price = 0;
                        $balanceReduce = 1;
                    } else if($allBalance >= $totalPrice){
                        //2. 平台通用余额 大于订单余额
                        $dis_price = $totalPrice;
                        $pay_price = 0;
                        $balanceReduce = 2;
                    } else if(($allBalance + $balance) >= $totalPrice){
                        //3. 平台通用余额 + 店铺余额 大于订单余额
                        $dis_price = $totalPrice;
                        $pay_price = 0;
                        $balanceReduce = 3;
                    }else {
                        $balanceReduce = 4;
                        // 4. 优先扣除  店铺余额 再扣除平台通用余额
                        $dis_price = $balance + $allBalance;
                        $pay_price = $totalPrice - $dis_price;
                    }
                }else{
                    if ($balance >= $totalPrice) {
                        $dis_price = $totalPrice;
                        $pay_price = 0;
                        $balanceReduce = 1;
                    } else {
                        $dis_price = $balance;
                        $pay_price = $totalPrice - $balance;
                        $balanceReduce = 4;

                    }

                }


            }
        }

        if($tmpHour  != $hour  ){

            if($tmpHour > $hour){
                $isBooked = -1;
                $min = $tmpHour*60;
                $time2 = strtotime("+" . $min . " minute", $time1);

                $shopRoomBookModel = new Shoproombook();
                $bookList = $shopRoomBookModel->where('room_id',$id)->where('status','in',['undo','doing'])->order('start_time','desc')->select();
                foreach ($bookList as $key=>$val){

                    $start = $val['start_time'];
                    $end = $val['end_time'];
                    if($time1 <=$start &&  $time2 >= $end) $isBooked = 1;//全包围
                    if($time1 >= $start && $time2 <= $end) $isBooked = 1;//在区间范围内
                    if($time1 <= $end && $time2 >$end) $isBooked = 1; //
                    if($time1 < $start && $time2 <=$end && $time2 >= $start) $isBooked = 1;

                }
                if($isBooked == 1){
                    $this->error("此时间段已被预定");
                }
            }
        }

        $userModel = new \app\admin\model\User();
        $user = $userModel->where('mobile',$mobile)->find();
        if(!$user){
            $db = array();
            $db['group_id'] = 1;
            $db['username'] = "微信用户";
            $db['mobile'] = $mobile;
            $db['createtime'] = time();
            $db['status'] = 'normal';
            $db['org_id'] = $orgId;
            $user_id = $userModel->insertGetId($db);
        }else{
            $user_id = $user['id'];
        }

        $daiUser = $this->auth->getUser();
        $orderNo = getOrderSn();
        $db = array();
        $db['shop_id'] = $shop['id'];
        $db['shop_name'] = $shop['name'];
        $db['room_id'] = $room['id'];
        $db['is_ktv'] = $room['is_ktv'];
        $db['room_name'] = $room['name'];
        $db['user_id'] = $user_id;
        $db['order_no'] = $orderNo;
        $db['create_time'] = time();
        $db['update_time'] = time();
        $db['amount'] = $orderPrice;
        $db['pay_amount'] = $pay_price;
        $db['book_start'] = $time1;
        $db['book_end'] = $time2;
        $db['set_id'] = $setId;
        $db['tuan_id'] = $tuanId;
        $db['balance'] = $dis_price;
        $db['mt_code'] = $mt_code;
        $db['dou_code'] = $dou_code;
        $db['dou_token'] = $douVerifyToken;
        $db['org_id'] = $orgId;
        $db['discount_id'] = $discountId;
        $db['is_dai'] = $daiUser['id'];
        $db['pay_rate'] = formatMoney($shop['pay_rate'] * $db['pay_amount'] / 100);
        $price = $pay_price-$db['pay_rate'];
        $db['rate'] = formatMoney($shop['ratio'] * $price / 100);
        $db['coupon_id'] = $couponId;
        $db['balance_type'] = $balanceReduce;
        $db['mt_trace_id'] = $meituan_trace_id;


        $code = mt_rand(100000, 999999);
        $db['open_code'] = "";

        $shopOrderModel = new Shoporder();
        $id = $shopOrderModel->insertGetId($db);
        $this->redis->rm($cacheKey);
        if ($id > 0) {

            if ($mt_code != "") {
                $userMtCodeModel->where('mt_code', $mtCode)->update(['status' => 'lock']);
            }
            if ($dou_code != "") {

                $userDouCodeModel->where('dou_code', $dou_code)->update(['status' => 'lock', 'order_id' => $id]);
            }

            $info = array();
            if ($pay_price > 0) {
                $userwxModel = new Userweixin();
                $wx = $userwxModel->where('user_id', $user['id'])->find();
                $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/order/sxfOrderCallback";

                $orgModel = new Org();
                $org = $orgModel->where('id', $orgId)->find();

                $shopMnoModel =new Shopmno();
                $shopMno = $shopMnoModel->where('shop_id',$shop['id'])->find();
                $mno = $org['mno'];
                if($shopMno){
                    if($shopMno['ratio'] == 100){
                        //走挂靠
                        $mno = $shopMno['mno'];
                    }else{
                        //走分账
                        $fusruleId = array();
                        $fusruleId['mno'] = $shopMno['mno'];

                        $realPay = formatMoney($pay_price- $pay_price*0.006);
                        $fusruleId['allotValue'] = formatMoney($shopMno['ratio']*$realPay/100);

                        $fs = array();
                        $fs[] = $fusruleId;
                        $req['fusruleId'] = $fs;
                    }
                }

                $req['mno'] = $mno;
                $req['ordNo'] = $orderNo;
                $req['amt'] = formatMoney($pay_price);

                $req['payType'] = "WECHAT";
                $req['payWay'] = "03";
                $req['subAppid'] = $org['app_id'];
                $req['userId'] = $wx['openid'];

                $req['subject'] = "包厢预定";
                $req['tradeSource'] = "01";
                $req['trmIp'] = get_client_ip();
                $req['notifyUrl'] = $url;


                $vbillService = new VbillService();
                $res = $vbillService->jsApi($req);
                $result = json_decode($res, true);
                $bizCode = $result['respData']['bizCode'];
                $bizMsg = $result['respData']['bizMsg'];

                if ($bizCode == '0000') {
                    $info['order_no'] = $orderNo;
                    $info['payInfo'] = $result['respData'];
                } else {
                    $this->error($bizMsg);
                }
            } else {

                $info['order_no'] = $orderNo;
                $info['payInfo'] = "";

                if ($tuanId != -1) {
                    $tuanUserModel->where('id', $tuanId)->update(['status' => 'used']);
                }

                if($discountId >0){

                    $userDiscountModel->where('id',$discountId)->update(['status'=>2]);

                }
                $order = $shopOrderModel->where('id', $id)->find();

                if ($mt_code != "") {
                    if($shop['mt2_token'] != ""){
                        $isChecked = $meituanService->consume($order);
                    }else{
                        $isChecked = $mtService->syncMt($order);

                    }
                    if ($isChecked == 0) $this->error("验券失败，请联系商家");

//                    if($mtPayPrice >0){
//                        $shopOrderModel->where('id',$order['id'])->update(['amount'=>$mtPayPrice]);
//                    }

                }

                if ($dou_code != "") {
                    $douService = new DouService();
                    $isChecked = $douService->verifyCode($order);
                    if ($isChecked == 0) $this->error("验券失败，请联系商家");

                }
                if($couponId != -1){
                    $userCouponModel = new Usercoupon();
                    $userCouponModel->where('id',$couponId)->update(['status'=>'used']);
                }

                $this->redis->set($order['shop_id'], time());

                $roomService = new RoomService();
                $roomService->addBookData($order);
                $shopOrderModel->where('id', $id)->update(['status' => 'payed', 'update_time' => time()]);


                if($dou_code != "" || $mt_code != ""){

                    $fromType = "";
                    if($mt_code != ""){
                        $fromType = "meituan";
                    }else{
                        $fromType = "douyin";
                    }
                    $shopMtDouProfitModel = new Shopmtdyprofit();
                    $mtDouProfit = $shopMtDouProfitModel->where('order_id',$id)->where('type',$fromType)->find();
                    if($mtDouProfit){

                        if ($shop['agent_ratio'] > 0) {

                            $userOrderProfitModel = new Userorderprofit();

                            $userModel = new \app\admin\model\User();
                            $tmpRatio = 0;
                            $agentUser = $userModel->where('id',$shop['agent_id'])->find();
                            if($agentUser['ref_uid'] != -1) {

                                $refRatio =$shop['agent_ratio']- $agentUser['ratio'] ;
                                $tmpRatio =  $agentUser['ratio'] ;
                                if($refRatio>0){
                                    $refFee = $refRatio* $mtDouProfit['amount'] / 100;
                                    if($refFee > 0){
                                        $userOrderProfitModel->insert(['order_id' => $order['id'], 'shop_id' => $order['shop_id'], 'type' => 'order',
                                            'user_id' => $agentUser['ref_uid'], 'create_time' => time(), 'amount' => formatMoney($refFee),'flag'=>'team']);
                                    }
                                }
                            }


                            $agentFee = ($shop['agent_ratio']-$tmpRatio)* $mtDouProfit['amount']/100 ;

                            if ($agentFee > 0) {
                                $userOrderProfitModel->insert(['order_id' => $order['id'], 'shop_id' => $order['shop_id'], 'type' => 'order',
                                    'user_id' => $shop['agent_id'], 'create_time' => time(), 'amount' => formatMoney($agentFee)]);
                            }


                        }
                    }

                }

                if ($type == "balance") {

                    $userBalanceModel = new Userbalance();
                    if($balanceReduce == 1){
                        $userBalanceModel->insert(['user_id' => $user['id'], 'type' => 'out',
                            'amount' => $dis_price, 'mark' => $shop['name'] . '预定抵扣', 'create_time' => time(), 'shop_id' => $shop['id'], 'order_id' => $id]);
                    }else if($balanceReduce == 2){

                        //划拨平台利润给店铺
                        $ratioList = $allBalanceModel->cacBalance($user['id'],$dis_price);
                        $shopProfit = 0;
                        foreach ($ratioList as $key=>$val){
                            $shopProfit += $val['amount']/$val['ratio'];
                            $allBalanceModel->insert(['ratio'=>$val['ratio'],'user_id'=>$user['id'],'type'=>'out','amount'=>$val['amount'],'create_time'=>time(),'from'=>'order','order_id'=>$id,'order_type'=>'qp']);
                        }

                        $shopProfit = formatMoney($shopProfit);
                        $shopMoney = $shopProfit-$shopProfit*0.006-$shopProfit*$shop['ratio']/100;
                        $shopBalanceProfitModel = new Shopbalanceprofit();
                        $shopBalanceProfitModel->insert(['shop_id'=>$shop['id'],'order_id'=>$id,'create_time'=>time(),'amount'=>$shopMoney,'order_type'=>'qp']);

                    }else if($balanceReduce == 3){
                        $userBalanceModel->insert(['user_id' => $user['id'], 'type' => 'out',
                            'amount' => $balance, 'mark' => $shop['name'] . '预定抵扣', 'create_time' => time(), 'shop_id' => $shop['id'], 'order_id' => $id]);
                        $orderAllBalance  = $dis_price - $balance;
                        $ratioList = $allBalanceModel->cacBalance($user['id'],$orderAllBalance);
                        $shopProfit = 0;
                        foreach ($ratioList as $key=>$val){
                            $shopProfit += $val['amount']/$val['ratio'];
                            $allBalanceModel->insert(['ratio'=>$val['ratio'],'user_id'=>$user['id'],'type'=>'out','amount'=>$val['amount'],'create_time'=>time(),'from'=>'order','order_id'=>$id,'order_type'=>'qp']);
                        }
                        //划拨平台利润给店铺
                        $shopProfit = formatMoney($shopProfit);
                        $shopMoney = $shopProfit-$shopProfit*0.006-$shopProfit*$shop['ratio']/100;
                        $shopBalanceProfitModel = new Shopbalanceprofit();
                        $shopBalanceProfitModel->insert(['shop_id'=>$shop['id'],'order_id'=>$id,'create_time'=>time(),'amount'=>$shopMoney,'order_type'=>'qp']);

                    }

                }

            }

            $this->success('下单成功', $info);
        } else {
            $this->error("订单生成失败,请联系客服");
        }

    }




    public function detail()
    {

        $order_no = $this->request->param("order_no");
        $shopOrderModel = new Shoporder();
        $order = $shopOrderModel->where('order_no', $order_no)->find();
        $order['tuan'] = "";
        if ($order['tuan_id'] != -1) {
            $shopTuanModel = new Shoptuan();
            $tuan = $shopTuanModel->where('id', $order['tuan_id'])->find();
            if ($tuan) {
                $order['tuan'] = $tuan['name'];
            }
        }

        if ($order['coupon_id'] != -1) {
            $userCouponModel = new Usercoupon();
            $coupon = $userCouponModel->where('id', $order['coupon_id'])->find();
            $shopCouponModel = new Shopcoupon();
            $shopCoupon = $shopCouponModel->where('id', $coupon['coupon_id'])->find();
            $order['coupon'] = $shopCoupon;
        }

        $shopDeviceModel = new Shopdevice();
        $device = $shopDeviceModel->where('room_id', $order['room_id'])->find();
        if ($device['is_bt'] == 1) {
            if ($order['open_code'] == "") {
                //生成蓝牙密码

                $deviceLockModel = new Devicelock();
                $lock = $deviceLockModel->where('room_id', $order['room_id'])->find();
                $lockService = new LockService();
                $param = array();
                $param['startDate'] = date("Y-m-d H:i:s", $order['book_start']);
                $param['endDate'] = date("Y-m-d H:i:s", $order['book_end']);
                $param['lockId'] = $lock['lockId'];
                $password = $lockService->getPassword($param);
                $shopOrderModel->where('id', $order['id'])->update(['open_code' => $password]);
            }
        }
        $order['discount_name'] = "";
        $order['discount_desc'] = "";
        if ($order['discount_id'] > 0) {

            $userDiscountModel = new Userdiscount();
            $shopDiscountModel = new Shopdiscount();

            $userDiscount = $userDiscountModel->where('id', $order['discount_id'])->find();
            $shopDiscount = $shopDiscountModel->where('id', $userDiscount['discount_id'])->find();
            if ($shopDiscount['discount_type'] == '时长抵扣') {
                $order['discount_desc'] = "时长抵扣:" . $shopDiscount['discount_val'] . "小时";
            } else if ($shopDiscount['discount_type'] == '金额抵扣') {
                $order['discount_desc'] = "金额抵扣:" . $shopDiscount['discount_val'] . "元";

            } else {
                $order['discount_desc'] = "折扣抵扣:" . $shopDiscount['discount_val'] . "折";
            }
            $order['discount_name'] = $shopDiscount['name'];

        }

        $order['hour'] = ($order['book_end'] - $order['book_start']) / 3600;
        $order['status_txt'] = $shopOrderModel->formatStatus($order['status']);
        $order['book_start'] = date("Y-m-d H:i:s", $order['book_start']);
        $order['book_end'] = date("Y-m-d H:i:s", $order['book_end']);

        $this->success('', $order);
    }


    public function payOrder()
    {

        $order_no = $this->request->param("order_no");
        $shopOrderModel = new Shoporder();
        $order = $shopOrderModel->where('order_no', $order_no)->find();
        if($order['status'] != "paying") $this->error("此订单不需要支付");


        $userwxModel = new Userweixin();
        $wx = $userwxModel->where('user_id', $order['user_id'])->find();
        $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/order/sxfOrderCallback";

        $orgModel = new Org();
        $org = $orgModel->where('id', $order['org_id'])->find();

        $shopMnoModel =new Shopmno();
        $shopMno = $shopMnoModel->where('shop_id',$order['shop_id'])->find();
        $pay_price = $order['pay_amount'];
        $mno = $org['mno'];
        if($shopMno){
            if($shopMno['ratio'] == 100){
                //走挂靠
                $mno = $shopMno['mno'];
            }else{
                //走分账
                $fusruleId = array();
                $fusruleId['mno'] = $shopMno['mno'];

                $realPay = formatMoney($pay_price- $pay_price*0.006);
                $fusruleId['allotValue'] = formatMoney($shopMno['ratio']*$realPay/100);

                $fs = array();
                $fs[] = $fusruleId;
                $req['fusruleId'] = $fs;
            }
        }

        $order_no = getOrderSn();
        $req['mno'] = $mno;
        $req['ordNo'] = $order_no;
        $req['amt'] = formatMoney($pay_price);

        $req['payType'] = "WECHAT";
        $req['payWay'] = "03";
        $req['subAppid'] = $org['app_id'];
        $req['userId'] = $wx['openid'];

        $req['subject'] = "包厢预定";
        $req['tradeSource'] = "01";
        $req['trmIp'] = get_client_ip();
        $req['notifyUrl'] = $url;


        $vbillService = new VbillService();
        $res = $vbillService->jsApi($req);
        $result = json_decode($res, true);
        $bizCode = $result['respData']['bizCode'];
        $bizMsg = $result['respData']['bizMsg'];

        if ($bizCode == '0000') {

            $info['order_no'] = $order_no;
            $info['payInfo'] = $result['respData'];
            $shopOrderModel->where('id', $order['id'])->update(['order_no'=>$order_no]);

            $this->success('',$info);
        } else {
            $this->error($bizMsg);
        }

    }

}
